//
//  AppDelegate.m
//  AlarmClock
//
//  Created by LF on 2017/4/26.
//  Copyright © 2017年 LF. All rights reserved.
//

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()
<
UNUserNotificationCenterDelegate
>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 使用 UNUserNotificationCenter 来管理通知
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    //监听回调事件
    center.delegate = self;
    
    //iOS 10 使用以下方法注册，才能得到授权
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              // Enable or disable features based on authorization.
                          }];
    
    //获取当前的通知设置，UNNotificationSettings 是只读对象，不能直接修改，只能通过以下方法获取
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        
    }];
    
    return YES;
}

#pragma mark - UNUserNotificationCenterDelegate   iOS10走这里
//在展示通知前进行处理，即有机会在展示通知前再修改通知内容。
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    
    // TODO 这个方法APP不在前台的时候似乎不走?
    
    //1. 处理通知
    
    // 收到推送的请求
    UNNotificationRequest *request = notification.request;
    
    // 收到的内容
    UNNotificationContent *content = request.content;
    
    // 收到消息的角标
    NSNumber *badge = content.badge;
    
    // 处理角标
    NSInteger currentBadge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    currentBadge += [badge integerValue];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = currentBadge;
    
    //2. 处理完成后条用 completionHandler ，用于指示在前台显示通知的形式
    completionHandler(UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    //收到推送的请求
    UNNotificationRequest *request = response.notification.request;
    
    //收到的内容
    UNNotificationContent *content = request.content;
    
    //收到用户的基本信息
    NSDictionary *userInfo = content.userInfo;
    
    //收到消息的角标
    NSNumber *badge = content.badge;
    
    //收到消息的body
    NSString *body = content.body;
    
    //收到消息的声音
    UNNotificationSound *sound = content.sound;
    
    //推送消息的副标题
    NSString *subtitle = content.subtitle;
    
    //推送消息的标题
    NSString *title = content.title;
    
    if ([response.notification.request.trigger isKindOfClass:[UNNotificationTrigger class]]) {
        NSLog(@"点击了通知:%@\n",userInfo);
    }
    else{
        NSLog(@"通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@}",body,title,subtitle,badge,sound,userInfo);
    }
    
    //处理消息的事件
    NSString *category = content.categoryIdentifier;
    
    NSLog(@"content.categoryIdentifier: %@",category);
    
    if ([category isEqualToString:@"comment"]) {
        [self handCommnet:response];
    }
    
    // 更新显示的徽章个数
    NSInteger APPBadge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    APPBadge--;
    APPBadge = APPBadge >= 0 ? APPBadge : 0;
    [UIApplication sharedApplication].applicationIconBadgeNumber = APPBadge;
    
    completionHandler();
}

- (void)handCommnet:(UNNotificationResponse *)response
{
    NSString *actionType = response.actionIdentifier;
    NSString *textStr = @"";
    
    if ([actionType isEqualToString:@"input"]) {
        UNTextInputNotificationResponse *temp = (UNTextInputNotificationResponse *)response;
        textStr = temp.userText;
    }
    else if ([actionType isEqualToString:@"open"])
    {
        textStr = @"open";
    }
    else if ([actionType isEqualToString:@"cancle"])
    {
        textStr = @"";
    }
    
    NSLog(@"你刚输入的内容是:%@",textStr);
}


#pragma mark - systemVersion < iOS 10.0 走这里
// 本地通知回调函数，当应用程序在前台时调用
// 用了 didReceiveNotificationResponse:withCompletionHandler: 这个方法之后这个就无效了
// Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]"
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    /*
     UIApplicationStateActive
     UIApplicationStateInactive
     UIApplicationStateBackground
     */
    if (application.applicationState == UIApplicationStateActive) {
        NSLog(@"UIApplicationStateActive");
        if ([UIDevice currentDevice].systemVersion.floatValue >= 10.0) {
            
            NSLog(@"这是iOS10,前台收到通知");
            
        } else {
            
            NSLog(@"这是iOS9,前台收到通知");
            
            UIAlertAction *a = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertAction *b = [UIAlertAction actionWithTitle:@"查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"好的,朕看过了");
                
            }];
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"您收到一条系统消息" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:a];
            [alert addAction:b];
            [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
        }
        
    } else if (application.applicationState == UIApplicationStateInactive) {
        NSLog(@"UIApplicationStateInactive");
    } else {
        NSLog(@"UIApplicationStateBackground");
    }
    
    // 更新显示的徽章个数
    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    badge--;
    badge = badge >= 0 ? badge : 0;
    [UIApplication sharedApplication].applicationIconBadgeNumber = badge;
}



@end
